import { defineStore } from 'pinia'
import { TicketService } from '../services/tickets'

export const useTicketsStore = defineStore('tickets', {
  state: () => ({
    tickets: [],
    loading: false,
    error: null,
    filters: {
      status: '',
      priority: '',
      category: '',
      assignee: '',
      keyword: '',
      dateRange: []
    },
    pagination: {
      page: 1,
      size: 20,
      total: 0
    },
    selectedTickets: [],
    bulkActions: {
      visible: false,
      action: '',
      loading: false
    }
  }),

  getters: {
    // 筛选后的工单
    filteredTickets: (state) => {
      let filtered = [...state.tickets]

      // 状态筛选
      if (state.filters.status) {
        filtered = filtered.filter(ticket => ticket.status === state.filters.status)
      }

      // 优先级筛选
      if (state.filters.priority) {
        filtered = filtered.filter(ticket => ticket.priority === state.filters.priority)
      }

      // 分类筛选
      if (state.filters.category) {
        filtered = filtered.filter(ticket => ticket.category === state.filters.category)
      }

      // 负责人筛选
      if (state.filters.assignee) {
        filtered = filtered.filter(ticket => ticket.assigneeId === state.filters.assignee)
      }

      // 关键词搜索
      if (state.filters.keyword) {
        const keyword = state.filters.keyword.toLowerCase()
        filtered = filtered.filter(ticket => 
          ticket.title.toLowerCase().includes(keyword) ||
          ticket.description.toLowerCase().includes(keyword) ||
          ticket.id.toString().includes(keyword)
        )
      }

      // 日期范围筛选
      if (state.filters.dateRange && state.filters.dateRange.length === 2) {
        const [startDate, endDate] = state.filters.dateRange
        filtered = filtered.filter(ticket => {
          const ticketDate = new Date(ticket.createdAt)
          return ticketDate >= startDate && ticketDate <= endDate
        })
      }

      return filtered
    },

    // 工单统计
    ticketStats: (state) => {
      const total = state.tickets.length
      const open = state.tickets.filter(t => t.status === 'OPEN').length
      const inProgress = state.tickets.filter(t => t.status === 'IN_PROGRESS').length
      const resolved = state.tickets.filter(t => t.status === 'RESOLVED').length
      const closed = state.tickets.filter(t => t.status === 'CLOSED').length
      const pending = state.tickets.filter(t => t.status === 'PENDING').length

      return {
        total,
        open,
        inProgress,
        resolved,
        closed,
        pending,
        resolutionRate: total > 0 ? Math.round((resolved / total) * 100) : 0
      }
    },

    // 优先级统计
    priorityStats: (state) => {
      return {
        high: state.tickets.filter(t => t.priority === 'HIGH').length,
        medium: state.tickets.filter(t => t.priority === 'MEDIUM').length,
        low: state.tickets.filter(t => t.priority === 'LOW').length
      }
    },

    // 分类统计
    categoryStats: (state) => {
      const categories = {}
      state.tickets.forEach(ticket => {
        categories[ticket.category] = (categories[ticket.category] || 0) + 1
      })
      return categories
    },

    // 是否有选中的工单
    hasSelectedTickets: (state) => state.selectedTickets.length > 0,

    // 选中的工单数量
    selectedCount: (state) => state.selectedTickets.length
  },

  actions: {
    // 添加新工单到本地状态（乐观更新）
    addTicketToState(ticket) {
      console.log(`[addTicketToState] 添加工单到本地状态:`, ticket.id)
      
      // 标准化数据
      const normalizedTicket = this.normalizeTicketData(ticket)
      
      // 检查是否已存在
      const existingIndex = this.tickets.findIndex(t => t.id === normalizedTicket.id)
      
      if (existingIndex !== -1) {
        // 如果已存在，更新它（以防数据有变化）
        console.log(`[addTicketToState] 工单已存在，更新: ${normalizedTicket.id}`)
        this.tickets[existingIndex] = normalizedTicket
      } else {
        // 添加到列表开头（最新的工单显示在最前面）
        console.log(`[addTicketToState] 添加新工单到列表开头`)
        this.tickets.unshift(normalizedTicket)
        
        // 更新总数
        if (this.pagination.total !== undefined) {
          this.pagination.total += 1
        }
      }
      
      console.log(`[addTicketToState] 当前工单数量: ${this.tickets.length}`)
    },
    
    // 获取工单列表
    async fetchTickets(params = {}) {
      console.log(`[fetchTickets] 开始获取工单列表...`)
      this.loading = true
      this.error = null
      
      try {
        // 构建请求参数
        // 注意：后端使用 0 基索引，前端使用 1 基索引，需要转换
        // 如果 params 中已经包含 page，优先使用它（假设它已经是 0 基索引）
        // 否则使用 store 中的 pagination.page（1 基索引）并转换为 0 基索引
        const pageParam = params.page !== undefined ? params.page : (this.pagination.page - 1)
        const requestParams = {
          ...params,
          page: pageParam, // 转换为 0 基索引（前端 page=1 对应后端 page=0）
          size: params.size !== undefined ? params.size : this.pagination.size
          // 移除 _t 参数，避免参数绑定冲突
        }
        
        console.log(`[fetchTickets] 请求参数:`, requestParams)
        console.log(`[fetchTickets] 前端页码: ${this.pagination.page}, 后端页码: ${requestParams.page}`)
        const result = await TicketService.list(requestParams)
        
        console.log(`[fetchTickets] 获取到数据:`, result)
        console.log(`[fetchTickets] 数据类型:`, typeof result)
        console.log(`[fetchTickets] 是否为数组:`, Array.isArray(result))
        console.log(`[fetchTickets] result.content:`, result?.content)
        console.log(`[fetchTickets] result.content 是否为数组:`, Array.isArray(result?.content))
        
        if (Array.isArray(result)) {
          // 直接是数组格式，标准化数据
          this.tickets = result.map(ticket => this.normalizeTicketData(ticket))
          console.log(`[fetchTickets] ✅ 设置工单列表（数组格式）: ${result.length} 个工单`)
        } else if (result && result.content && Array.isArray(result.content)) {
          // 处理分页响应格式: {content: [...], page: 1, size: 20, totalElements: 30, totalPages: 2}
          // 标准化数据：将 assignedToName 映射为 assigneeName
          this.tickets = result.content.map(ticket => this.normalizeTicketData(ticket))
          this.pagination.total = result.totalElements || result.total || 0
          this.pagination.page = result.page || 1
          this.pagination.size = result.size || 20
          console.log(`[fetchTickets] ✅ 设置分页工单列表: ${result.content.length} 个工单，总数: ${result.totalElements}`)
        } else if (result && result.records && Array.isArray(result.records)) {
          // 处理其他分页格式，标准化数据
          this.tickets = result.records.map(ticket => this.normalizeTicketData(ticket))
          this.pagination.total = result.total || 0
          console.log(`[fetchTickets] ✅ 设置工单列表（records格式）: ${result.records.length} 个工单，总数: ${result.total}`)
        } else {
          // 未获取到有效数据
          this.tickets = []
          console.warn(`[fetchTickets] ⚠️ 未获取到有效数据，收到的数据结构:`, result)
          console.warn(`[fetchTickets] ⚠️ result 的键:`, result ? Object.keys(result) : 'result 为 null/undefined')
          
          // 如果后端返回了消息，显示给用户
          if (result && result.message) {
            console.warn(`[fetchTickets] ⚠️ 后端消息:`, result.message)
          }
        }
        
        console.log(`[fetchTickets] ✅ 获取工单列表完成，当前数量: ${this.tickets.length}`)
        console.log(`[fetchTickets] 📋 工单列表预览:`, this.tickets.slice(0, 3))
      } catch (error) {
        this.error = error?.message || String(error)
        this.tickets = []
        console.error(`[fetchTickets] ❌ 获取工单列表失败:`, error)
      } finally {
        this.loading = false
      }
    },

    // 创建工单
    async createTicket(ticketData) {
      const storeActionId = `STORE-${Date.now()}`
      
      console.log('┌─────────────────────────────────────────────────┐')
      console.log(`│ 🏪 [${storeActionId}] Store: createTicket 开始`)
      console.log('└─────────────────────────────────────────────────┘')
      console.log(`📦 [${storeActionId}] 接收到的工单数据:`, JSON.stringify(ticketData, null, 2))
      console.log(`📊 [${storeActionId}] 当前工单列表长度:`, this.tickets.length)
      
      this.loading = true
      this.error = null
      
      try {
        console.log(`🔄 [${storeActionId}] 调用 TicketService.create()...`)
        const result = await TicketService.create(ticketData)
        
        console.log(`📥 [${storeActionId}] TicketService 返回结果:`, result ? JSON.stringify(result, null, 2) : 'null')
        
        if (result) {
          console.log(`✅ [${storeActionId}] 创建成功！`)
          
          // 🎯 策略1：立即添加新工单到本地状态（乐观更新）
          console.log(`🚀 [${storeActionId}] 立即将新工单添加到本地状态...`)
          this.addTicketToState(result)
          console.log(`📊 [${storeActionId}] 乐观更新后工单数量:`, this.tickets.length)
          
          // 🎯 策略2：后台刷新确保数据一致性（双重保障）
          console.log(`🔄 [${storeActionId}] 后台刷新工单列表以确保数据一致性...`)
          // 使用 Promise.allSettled 避免刷新失败影响返回
          Promise.allSettled([
            this.fetchTickets()
          ]).then(([fetchResult]) => {
            if (fetchResult.status === 'fulfilled') {
              console.log(`✅ [${storeActionId}] 后台刷新成功`)
            } else {
              console.warn(`⚠️ [${storeActionId}] 后台刷新失败，但乐观更新已生效:`, fetchResult.reason)
            }
          })
          
          // 🎯 策略3：验证新工单
          console.log(`🔍 [${storeActionId}] 验证新工单是否在列表中...`)
          const foundTicket = this.tickets.find(t => t.id === result.id)
          if (foundTicket) {
            console.log(`✅ [${storeActionId}] 新工单已在列表中:`, foundTicket.ticketNumber || foundTicket.id)
          } else {
            console.error(`❌ [${storeActionId}] 新工单未在列表中！这不应该发生！`)
            console.log(`📋 [${storeActionId}] 当前工单列表IDs:`, this.tickets.map(t => t.id))
          }
          
          console.log('┌─────────────────────────────────────────────────┐')
          console.log(`│ ✅ [${storeActionId}] Store: createTicket 成功`)
          console.log(`│    工单ID: ${result.id}`)
          console.log(`│    工单编号: ${result.ticketNumber || 'N/A'}`)
          console.log(`│    列表数量: ${this.tickets.length}`)
          console.log('└─────────────────────────────────────────────────┘')
          
          return { success: true, data: result }
        }
        
        console.warn(`⚠️ [${storeActionId}] TicketService 返回 null`)
        console.log('┌─────────────────────────────────────────────────┐')
        console.log(`│ ❌ [${storeActionId}] Store: createTicket 失败`)
        console.log('└─────────────────────────────────────────────────┘')
        return { success: false, message: '创建工单失败' }
      } catch (error) {
        this.error = error?.message || String(error)
        console.error('┌─────────────────────────────────────────────────┐')
        console.error(`│ ❌ [${storeActionId}] Store: createTicket 异常`)
        console.error('└─────────────────────────────────────────────────┘')
        console.error(`❌ [${storeActionId}] 异常信息:`, error)
        console.error(`❌ [${storeActionId}] 错误消息:`, this.error)
        return { success: false, message: this.error }
      } finally {
        this.loading = false
        console.log(`🏁 [${storeActionId}] Store 操作完成`)
      }
    },

    // 更新工单
    async updateTicket(ticketId, updateData) {
      this.loading = true
      this.error = null
      try {
        const result = await TicketService.update(ticketId, updateData)
        if (result) {
          // 更新本地数据
          const index = this.tickets.findIndex(t => t.id === ticketId)
          if (index !== -1) {
            this.tickets[index] = { ...this.tickets[index], ...updateData }
          }
          return { success: true, data: result }
        }
        return { success: false, message: '更新工单失败' }
      } catch (error) {
        this.error = error?.message || String(error)
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    // 删除工单
    async deleteTicket(ticketId) {
      this.loading = true
      this.error = null
      try {
        const result = await TicketService.delete(ticketId)
        if (result) {
          // 从本地列表中移除
          this.tickets = this.tickets.filter(t => t.id !== ticketId)
          return { success: true }
        }
        return { success: false, message: '删除工单失败' }
      } catch (error) {
        this.error = error?.message || String(error)
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    // 更新工单状态
    async updateTicketStatus(ticketId, status, note = '') {
      this.loading = true
      this.error = null
      try {
        console.log(`[updateTicketStatus] 开始更新工单状态: ticketId=${ticketId}, status=${status}`)
        const result = await TicketService.updateStatus(ticketId, status, note)
        console.log(`[updateTicketStatus] 后端返回结果:`, result)
        
        if (result) {
          // 标准化后端返回的数据
          const normalizedResult = this.normalizeTicketData(result)
          console.log(`[updateTicketStatus] 标准化后的数据:`, normalizedResult)
          
          // 更新本地数据 - 使用splice确保Pinia响应式更新
          const ticketIndex = this.tickets.findIndex(t => t.id === ticketId)
          if (ticketIndex !== -1) {
            // 创建更新后的工单对象
            let updatedTicket
            if (normalizedResult.id) {
              // 如果后端返回了完整数据，使用后端数据合并
              updatedTicket = { 
                ...this.tickets[ticketIndex], 
                ...normalizedResult,
                status: normalizedResult.status || status  // 确保状态被更新
              }
            } else {
              // 否则只更新状态和更新时间
              updatedTicket = {
                ...this.tickets[ticketIndex],
                status: status,
                updatedAt: result.updatedAt || new Date().toISOString()
              }
            }
            
            // 使用splice替换数组元素，确保Pinia响应式系统能够检测到变化
            this.tickets.splice(ticketIndex, 1, updatedTicket)
            
            console.log(`[updateTicketStatus] ✅ 本地数据已更新，索引: ${ticketIndex}`)
            console.log(`[updateTicketStatus] 更新后的工单状态:`, this.tickets[ticketIndex].status)
            console.log(`[updateTicketStatus] 更新后的工单数据:`, this.tickets[ticketIndex])
          } else {
            console.warn(`[updateTicketStatus] ⚠️ 未找到要更新的工单: ticketId=${ticketId}`)
            console.log(`[updateTicketStatus] 当前工单列表IDs:`, this.tickets.map(t => t.id))
          }
          
          return { success: true, data: normalizedResult }
        }
        return { success: false, message: '更新工单状态失败' }
      } catch (error) {
        this.error = error?.message || String(error)
        console.error(`[updateTicketStatus] ❌ 更新失败:`, error)
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    // 指派工单
    async assignTicket(ticketId, assignee) {
      this.loading = true
      this.error = null
      try {
        // 提取assigneeId - 支持对象和ID两种格式
        const assigneeId = assignee?.id || assignee
        const assigneeName = assignee?.name || assignee?.fullName || assignee?.username
        
        if (!assigneeId) {
          return { success: false, message: '指派人ID不能为空' }
        }
        
        console.log(`[assignTicket] 指派工单: ticketId=${ticketId}, assigneeId=${assigneeId}, assigneeName=${assigneeName}`)
        
        const result = await TicketService.assign(ticketId, assigneeId, assigneeName)
        if (result) {
          // 更新本地数据 - 使用splice确保Pinia响应式更新
          const ticketIndex = this.tickets.findIndex(t => t.id === ticketId)
          if (ticketIndex !== -1) {
            // 创建更新后的工单对象
            let updatedTicket
            if (result.id) {
              // 如果后端返回了完整数据，使用后端数据并标准化
              const normalizedResult = this.normalizeTicketData(result)
              updatedTicket = { 
                ...this.tickets[ticketIndex], 
                ...normalizedResult 
              }
            } else {
              // 否则只更新已知字段
              updatedTicket = {
                ...this.tickets[ticketIndex],
                assigneeId: assigneeId,
                assigneeName: assigneeName,
                status: 'IN_PROGRESS'
              }
            }
            
            // 使用splice替换数组元素，确保Pinia响应式系统能够检测到变化
            this.tickets.splice(ticketIndex, 1, updatedTicket)
            console.log(`[assignTicket] ✅ 本地数据已更新，索引: ${ticketIndex}`)
          }
          return { success: true, data: result }
        }
        return { success: false, message: '指派工单失败' }
      } catch (error) {
        this.error = error?.message || String(error)
        console.error(`[assignTicket] 指派工单失败:`, error)
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },

    // 标准化工单数据，将后端字段名映射为前端期望的字段名
    normalizeTicketData(ticket) {
      if (!ticket) return ticket
      
      // 创建标准化后的对象
      const normalized = { ...ticket }
      
      // 映射负责人字段：assignedToName -> assigneeName, assignedToId -> assigneeId
      if (ticket.assignedToName !== undefined) {
        normalized.assigneeName = ticket.assignedToName
      }
      if (ticket.assignedToId !== undefined) {
        normalized.assigneeId = ticket.assignedToId
      }
      
      // 映射分类字段：categoryName -> category
      if (ticket.categoryName !== undefined) {
        normalized.category = ticket.categoryName
      }
      if (ticket.categoryId !== undefined) {
        normalized.categoryId = ticket.categoryId
      }
      
      return normalized
    },

    // 批量操作
    async bulkAction(action, ticketIds, data = {}) {
      this.bulkActions.loading = true
      this.error = null
      try {
        const result = await TicketService.bulkAction(action, ticketIds, data)
        if (result) {
          // 刷新工单列表
          await this.fetchTickets()
          this.selectedTickets = []
          return { success: true, data: result }
        }
        return { success: false, message: '批量操作失败' }
      } catch (error) {
        this.error = error?.message || String(error)
        return { success: false, message: this.error }
      } finally {
        this.bulkActions.loading = false
      }
    },

    // 设置筛选条件
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters }
      this.pagination.page = 1 // 重置到第一页
    },

    // 清除筛选条件
    clearFilters() {
      this.filters = {
        status: '',
        priority: '',
        category: '',
        assignee: '',
        keyword: '',
        dateRange: []
      }
      this.pagination.page = 1
    },

    // 设置分页
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
    },

    // 选择工单
    selectTicket(ticketId) {
      if (!this.selectedTickets.includes(ticketId)) {
        this.selectedTickets.push(ticketId)
      }
    },

    // 取消选择工单
    unselectTicket(ticketId) {
      this.selectedTickets = this.selectedTickets.filter(id => id !== ticketId)
    },

    // 全选工单
    selectAllTickets() {
      this.selectedTickets = this.filteredTickets.map(ticket => ticket.id)
    },

    // 取消全选
    unselectAllTickets() {
      this.selectedTickets = []
    },

    // 切换工单选择状态
    toggleTicketSelection(ticketId) {
      if (this.selectedTickets.includes(ticketId)) {
        this.unselectTicket(ticketId)
      } else {
        this.selectTicket(ticketId)
      }
    },

    // 显示批量操作对话框
    showBulkActions(action) {
      this.bulkActions.action = action
      this.bulkActions.visible = true
    },

    // 隐藏批量操作对话框
    hideBulkActions() {
      this.bulkActions.visible = false
      this.bulkActions.action = ''
    },

    // 获取工单详情
    async getTicketDetail(ticketId) {
      try {
        const result = await TicketService.getDetail(ticketId)
        return result
      } catch (error) {
        console.error('获取工单详情失败:', error)
        return null
      }
    },

    // 添加工单评论
    async addComment(ticketId, comment) {
      try {
        const result = await TicketService.addComment(ticketId, comment)
        if (result) {
          // 更新本地工单数据
          const ticket = this.tickets.find(t => t.id === ticketId)
          if (ticket) {
            ticket.comments = ticket.comments || []
            ticket.comments.push(result)
          }
          return { success: true, data: result }
        }
        return { success: false, message: '添加评论失败' }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    // 添加工单附件
    async addAttachment(ticketId, file) {
      try {
        const result = await TicketService.addAttachment(ticketId, file)
        if (result) {
          // 更新本地工单数据
          const ticket = this.tickets.find(t => t.id === ticketId)
          if (ticket) {
            ticket.attachments = ticket.attachments || []
            ticket.attachments.push(result)
          }
          return { success: true, data: result }
        }
        return { success: false, message: '添加附件失败' }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    // 导出工单
    async exportTickets(format = 'excel') {
      try {
        const result = await TicketService.export(this.filters, format)
        return { success: true, data: result }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    // 导入工单
    async importTickets(file) {
      try {
        const result = await TicketService.import(file)
        if (result) {
          // 刷新工单列表
          await this.fetchTickets()
          return { success: true, data: result }
        }
        return { success: false, message: '导入工单失败' }
      } catch (error) {
        return { success: false, message: error.message }
      }
    }
  }
})